import "antd/lib/message/style/css";
import _message from "antd/lib/message";
import "antd/lib/notification/style/css";
import _notification from "antd/lib/notification";

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
// import { getDvaApp } from 'umi';
import { extend } from 'umi-request';
import qs from 'qs';
import localStorage from '../utils/localStorage';
import { getConfigure } from '../utils/configure'; // 获取默认配置

var constant = {
  LOGIN_TIMEOUT: '00999'
}; // const debounce = function (func, delay = 1000) {
//   let timeout = null;
//   return function (...res) {
//     clearTimeout(timeout)
//     timeout = setTimeout(() => {
//       func.apply(this, res)
//     }, delay)
//   }
// }

function debounce(fn) {
  var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;
  var timerId = null;
  var flag = true;
  return function () {
    clearTimeout(timerId);

    if (flag) {
      for (var _len = arguments.length, res = new Array(_len), _key = 0; _key < _len; _key++) {
        res[_key] = arguments[_key];
      }

      fn.apply(this, res);
      flag = false;
    }

    timerId = setTimeout(function () {
      flag = true;
    }, wait);
  };
}

var codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。'
};
/**
 * 异常处理程序
 */

var errorHandler = function errorHandler(error) {
  var response = error.response;

  if (response && response.status) {
    var errorText = codeMessage[response.status] || response.statusText;
    var status = response.status,
        url = response.url;

    _notification.error({
      message: "\u8BF7\u6C42\u9519\u8BEF ".concat(status, ": ").concat(url),
      description: errorText
    });
  } else if (!response) {
    _notification.error({
      description: '您的网络发生异常，无法连接服务器',
      message: '网络异常'
    });
  }

  return response;
};
/**
 * 封装请求
 * @param {Sting} apiKey // key常量。ex: LOGIN_ACCOUNT
 * @param {Object} params // 数据参数。ex：{ data: {}, method: 'GET', showSuccessToast: false, showErrorToast: true  }
 */


var request = extend({
  errorHandler: errorHandler,
  // 默认错误处理
  credentials: 'omit',
  // 不带上cookie
  headers: {
    'Content-Type': 'application/json; charset=utf-8',
    Client: getConfigure().client
  },
  paramsSerializer: function paramsSerializer(params) {
    return qs.stringify(params, {
      allowDots: true
    });
  }
}); // request拦截器, 改变url

request.interceptors.request.use(function (url, options) {
  debugger; // 简化传值

  var method = options.method ? String(options.method).toUpperCase() : 'GET';
  return {
    url: getConfigure().apiPrefix + (getConfigure().api[url] || url),
    options: _objectSpread(_objectSpread({}, options), {}, {
      interceptors: true,
      headers: _objectSpread(_objectSpread({}, options.headers), {}, {
        authorization: localStorage.getItem('token')
      }),
      params: method === 'GET' ? options.data : {},
      data: method !== 'GET' ? options.data : undefined
    })
  };
}); // 防抖  warning 提示，防止多次弹出

var warningMessage = debounce(function (res, fun) {
  _message.warning(res.message);

  fun();
}, 2000); // 在返回数据前处理一些逻辑

request.use( /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(ctx, next) {
    var req, res, options, _options$showSuccessT, showSuccessToast, _options$showErrorToa, showErrorToast;

    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return next();

          case 2:
            // 统一处理业务错误、退出登录
            req = ctx.req, res = ctx.res;
            options = req.options;
            _options$showSuccessT = options.showSuccessToast, showSuccessToast = _options$showSuccessT === void 0 ? 0 : _options$showSuccessT, _options$showErrorToa = options.showErrorToast, showErrorToast = _options$showErrorToa === void 0 ? 1 : _options$showErrorToa; // 返回成功并且需要提示

            if (showSuccessToast && res.success) {
              _message.success(res.message);
            } // 登录过期


            if (res.resultCode === constant.LOGIN_TIMEOUT) {
              // message.warning(res.message);
              // 防抖提示
              warningMessage(res, function () {// eslint-disable-next-line no-underscore-dangle
                // getDvaApp()._store.dispatch({ type: 'login/logout' });
              });
            } // 错误提示


            if (showErrorToast && !res.success && res.resultCode !== constant.LOGIN_TIMEOUT) {
              if (res.resultCode !== '0005') {
                // 重置密码不需要提示
                _message.error(res.message);
              }
            }

          case 8:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));

  return function (_x, _x2) {
    return _ref.apply(this, arguments);
  };
}());
export default request;